package com.liuyongqi.accountbook;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.List;

public class AllActivity extends AppCompatActivity {

    private ListView list_item;
    String type = "";

    private DetailAdapter adapter;
    private NotesDBHelper helper;
    private SQLiteDatabase dbReader;
    private Cursor cursor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_all);

        list_item = findViewById(R.id.list_item);
        type = getIntent().getStringExtra("type");
        helper = new NotesDBHelper(this);
        dbReader = helper.getReadableDatabase();
        cursor = dbReader.query(NotesDBHelper.TABLE_NAME, null, null, null,null, null, null);
        adapter = new DetailAdapter(AllActivity.this,query(type));
        list_item.setAdapter(adapter);
        list_item.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                cursor.moveToPosition(position);
                Intent intent = new Intent(AllActivity.this, Detail.class);
                intent.putExtra(NotesDBHelper.ID, cursor.getInt(cursor.getColumnIndex(NotesDBHelper.ID)));
                intent.putExtra(NotesDBHelper.TYPE, cursor.getString(cursor.getColumnIndex(NotesDBHelper.TYPE)));
                intent.putExtra(NotesDBHelper.MONEY, cursor.getString(cursor.getColumnIndex(NotesDBHelper.MONEY)));
                intent.putExtra(NotesDBHelper.PATH, cursor.getString(cursor.getColumnIndex(NotesDBHelper.PATH)));
                startActivityForResult(intent,100);
            }
        });
    }


    private List<NoteInfo> query(String _type) {
          List<NoteInfo> list = new ArrayList<>();
          List<NoteInfo> _list = new ArrayList<>();
        _list.clear();
        list.clear();
          Cursor cursor = dbReader.query (NotesDBHelper.TABLE_NAME,null,null,null,null,null,null);
        while (cursor.moveToNext()) {
            String type = cursor.getString(1);
            String money = cursor.getString(2);
            String path = cursor.getString(3);
            if ("0".equals(_type) && "收入".equals(type)) {
                list.add(new NoteInfo(type, money, path));
            } else if ("1".equals(_type) && "支出".equals(type)) {
                _list.add(new NoteInfo(type, money, path));

            }
        }
        if("0".equals(_type)){
            return list;
        }else {
            return _list;
        }

    }
}